﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InfoStuffStore.Common;

namespace InfoStuffStore
{
    public partial class FormBuyAdSpace : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtTitle.Text == "" && txtEmail.Text == "" && txtName.Text == "" && txtWebsite.Text == "" && ddlPlan.SelectedIndex == 0 && !fileImage.HasFile)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('All fields are required!');", true);
                return;
            }
            string transCode = string.Empty;
            try
            {
                Session["stage"] = Constants.ENVIRONMENT;
                SetProfile.SessionProfile = SetProfile.CreateAPIProfile(Constants.API_USERNAME, Constants.API_PASSWORD, Constants.API_SIGNATURE, "", "", Constants.ENVIRONMENT, Constants.SUBJECT, Constants.OAUTH_SIGNATURE, Constants.OAUTH_TOKEN, Constants.OAUTH_TIMESTAMP);
                string amount = ddlPlan.SelectedValue;
                transCode = Guid.NewGuid().ToString().Replace("-","");
                fileImage.SaveAs(Server.MapPath(string.Format("~/Content/AdSpace/{0}.png", transCode)));
                using (DBDataContext dataContext = new DBDataContext())
                {
                    AdSpace adspace = new AdSpace()
                    {
                        EmailID = txtEmail.Text,
                        ImagePath = string.Format("{0}.png", transCode),
                        IsActive = false,
                        Name = txtName.Text,
                        SelectPlan = ddlPlan.SelectedValue,
                        SiteLink = txtWebsite.Text,
                        Title = txtTitle.Text,
                        TransCode = transCode,
                        ExpiryaDate = null
                    };

                    dataContext.AdSpaces.InsertOnSubmit(adspace);
                    dataContext.SubmitChanges();
                }

                string url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port;
                string cancelURL = url + ResolveUrl("BuyAdSpace.aspx");

                com.paypal.sdk.services.NVPCallerServices caller = PayPalAPI.PayPalAPIInitialize();
                com.paypal.sdk.util.NVPCodec encoder = new com.paypal.sdk.util.NVPCodec();
                encoder["METHOD"] = "SetExpressCheckout";
                encoder["CANCELURL"] = cancelURL;
                encoder["PAYMENTACTION"] = "Sale";
                encoder["CURRENCYCODE"] = "USD";

                encoder["L_NAME0"] = "AdSpace - Infostuffstore.com";
                encoder["L_NUMBER0"] = "Ads Display";
                encoder["L_DESC0"] = "AdSpace - Infostuffstore.com";
                encoder["L_AMT0"] = amount;
                encoder["L_QTY0"] = "1";

                encoder["ITEMAMT"] = amount;

                encoder["AMT"] = amount;
                string returnURL = url + ResolveUrl("GetCheckoutDetails.aspx") + "?currency=USD&paymentType=Sale&amount=" + amount + "&tid=" + transCode;

                encoder["RETURNURL"] = returnURL;
                encoder["MAXAMT"] = amount;
                // encoder["CALLBACK"] = "https://www.ppcallback.com/callback.pl";


                encoder["CALLBACKTIMEOUT"] = "4";
                string pStrrequestforNvp = encoder.Encode();
                string pStresponsenvp = caller.Call(pStrrequestforNvp);

                com.paypal.sdk.util.NVPCodec decoder = new com.paypal.sdk.util.NVPCodec();
                decoder.Decode(pStresponsenvp);

                string strAck = decoder["ACK"];
                if (strAck != null && (strAck == "Success" || strAck == "SuccessWithWarning"))
                {
                    Session["TOKEN"] = decoder["TOKEN"];
                    //string host = "www." + Session["stage"].ToString() + ".paypal.com";
                    string host = "www.paypal.com";
                    //string ECURL = "https://" + host + "/cgi-bin/webscr?token=" + decoder["TOKEN"];
                    string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + decoder["TOKEN"];
                    Response.Redirect(ECURL);
                }
                else
                {
                    Session["errorresult"] = decoder;
                    string pStrResQue = "API=" + "Error Detail ";
                    Response.Redirect("APIError.aspx?" + pStrResQue);
                }

            }
            catch
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Error initiating the payment!!');", true);
            }
        }
    }
}